package net.gazhi.delonix.core.web;

import java.text.SimpleDateFormat;

import net.gazhi.delonix.core.convert.CustomArrayEditor;
import net.gazhi.delonix.core.convert.CustomSqlDateEditor;
import net.gazhi.delonix.core.validation.ExposeValueToArgsBindingErrorProcessor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.AbstractBindingResult;
import org.springframework.validation.DefaultMessageCodesResolver;
import org.springframework.validation.DefaultMessageCodesResolver.Format;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

/**
 * 基于注解的 Controller 基类
 * 
 * @author Jeffrey Lin
 * 
 */
public class AbstractAnnotationController {

	protected Log logger = LogFactory.getLog(this.getClass());

	/**
	 * 初始化请求数据邦定器，实现数据类型自动转换
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {

		// 把 value 暴露为 FieldError 第 {0} 个 message 参数
		binder.setBindingErrorProcessor(new ExposeValueToArgsBindingErrorProcessor());

		// 错误消息的 message code 格式改为后置的
		AbstractBindingResult result = (AbstractBindingResult) binder.getBindingResult();
		DefaultMessageCodesResolver messageCodesResolver = (DefaultMessageCodesResolver) result.getMessageCodesResolver();
		messageCodesResolver.setMessageCodeFormatter(Format.POSTFIX_ERROR_CODE);

		// 清除字符串前后的空格
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));

		// 设置绑定日期类型的格式
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(dateFormat, true));
		binder.registerCustomEditor(java.sql.Date.class, new CustomSqlDateEditor(dateFormat, true));

		// 自定义的数组转换器
		binder.registerCustomEditor(String[].class, new CustomArrayEditor(String.class, binder.getConversionService()));
		binder.registerCustomEditor(Integer[].class, new CustomArrayEditor(Integer.class, binder.getConversionService()));
		binder.registerCustomEditor(Long[].class, new CustomArrayEditor(Long.class, binder.getConversionService()));
		binder.registerCustomEditor(Float[].class, new CustomArrayEditor(Float.class, binder.getConversionService()));
		binder.registerCustomEditor(Double[].class, new CustomArrayEditor(Double.class, binder.getConversionService()));

	}

}
